
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next

class Solution:

    def connect(self, root):
        import collections
        if not root:
            return root
        queue = collections.deque()
        queue.append(root)
        while queue:
            node_now = queue.popleft()
            length = len(queue)
            if node_now.left:
                queue.append(node_now.left)
            if node_now.right:
                queue.append(node_now.right)
            for i in range(length):
                T = queue.popleft()
                node_now.next = T
                if T.left:
                    queue.append(T.left)
                if T.right:
                    queue.append(T.right)
                node_now = T
            node_now.next = None
        return root




